from flask import Flask, request, jsonify, send_from_directory
from flask_cors import CORS
import os
import time
import uuid
import json

app = Flask(__name__)
CORS(app)

# 获取后端目录的绝对路径
BACKEND_DIR = os.path.dirname(os.path.abspath(__file__))

# 图片和参数保存路径（使用绝对路径）
UPLOAD_FOLDER = os.path.join(BACKEND_DIR, 'uploads')
RESULT_FOLDER = os.path.join(BACKEND_DIR, 'results')
PARAMS_FOLDER = os.path.join(BACKEND_DIR, 'params')
DEFAULT_RESULT_IMAGE = 'gemini-edited-image.png'  # 系统默认图片名称

# 确保目录存在
os.makedirs(UPLOAD_FOLDER, exist_ok=True)
os.makedirs(RESULT_FOLDER, exist_ok=True)
os.makedirs(PARAMS_FOLDER, exist_ok=True)

print(f"上传文件夹路径: {UPLOAD_FOLDER}")
print(f"结果文件夹路径: {RESULT_FOLDER}")
print(f"参数文件夹路径: {PARAMS_FOLDER}")

def run_python_script(interpreter_path, script_path):
    command = f"{interpreter_path} {script_path}"
    exit_code = os.system(command)
    if exit_code == 0:
        print("脚本执行成功！")
    else:
        print(f"脚本执行失败，退出码：{exit_code}")

# 添加静态文件访问路由
@app.route('/uploads/<path:filename>')
def serve_upload(filename):
    return send_from_directory(UPLOAD_FOLDER, filename)

@app.route('/results/<path:filename>')
def serve_result(filename):
    # 无论请求什么文件名，都返回默认图片
    return send_from_directory(RESULT_FOLDER, DEFAULT_RESULT_IMAGE)

@app.route('/api/upload', methods=['POST'])
def upload_image():
    if 'image' not in request.files:
        return jsonify({'error': '没有上传图片'}), 400
    
    file = request.files['image']
    if file.filename == '':
        return jsonify({'error': '没有选择文件'}), 400
    
    # 获取用户参数
    params = {}
    for key in request.form:
        # 处理复杂参数（如数组和对象）
        if key in ['colorPreference', 'fabricPreference', 'pattern']:
            # 这些是多选字段，前端传来的是逗号分隔的字符串
            value = request.form[key]
            if value:  # 确保值不为空
                params[key] = value.split(',')
            else:
                params[key] = []
        else:
            params[key] = request.form[key]
    
    # 生成唯一ID
    unique_id = str(uuid.uuid4())
    
    # 保存图片
    filename = f"{unique_id}_{file.filename}"
    file_path = os.path.join(UPLOAD_FOLDER, filename)
    file.save(file_path)
    print(f"保存上传图片到: {file_path}")
    
    # 保存参数到txt文件
    params_path = os.path.join(PARAMS_FOLDER, f"{unique_id}_params.txt")
    with open(params_path, 'w', encoding='utf-8') as f:
        for key, value in params.items():
            if isinstance(value, list):
                f.write(f"{key}: {', '.join(value)}\n")
            else:
                f.write(f"{key}: {value}\n")
    print(f"保存参数到: {params_path}")

    print("开始执行脚本......\n")
    interpreter_path = "F:/VueProject/img/genai-env/Scripts/python.exe"  # Python 解释器路径
    script_path = "backend/model/test.py"  # 目标脚本路径
    run_python_script(interpreter_path, script_path)

    # 返回URL格式的路径
    return jsonify({
        'success': True,
        'original_image': f'/uploads/{filename}',
        'result_image': f'/results/{DEFAULT_RESULT_IMAGE}',  # 始终返回默认图片路径
        'message': '图片上传成功，参数已保存',
        'params': params
    })

@app.route('/api/params/list', methods=['GET'])
def list_params():
    """获取所有已保存的参数文件列表"""
    params_files = []
    for filename in os.listdir(PARAMS_FOLDER):
        if filename.endswith('_params.txt'):  # 改用txt文件作为参数存储
            unique_id = filename.split('_params.txt')[0]
            params_path = os.path.join(PARAMS_FOLDER, filename)
            
            # 从txt文件读取参数
            params = {}
            with open(params_path, 'r', encoding='utf-8') as f:
                for line in f:
                    if ':' in line:
                        key, value = line.strip().split(':', 1)
                        params[key.strip()] = value.strip()
            
            # 查找对应的原始图片
            original_image = None
            for img_file in os.listdir(UPLOAD_FOLDER):
                if img_file.startswith(unique_id):
                    original_image = f'/uploads/{img_file}'
                    break
            
            # 创建一个参数摘要
            summary = f"{params.get('gender', '未知')}"
            if 'clothingType' in params:
                summary += f", {params.get('clothingType', '')}"
            if 'style' in params:
                summary += f", {params.get('style', '')}风格"
            
            params_files.append({
                'id': unique_id,
                'date': time.strftime('%Y-%m-%d %H:%M', time.localtime(os.path.getctime(params_path))),
                'originalImage': original_image,
                'resultImage': f'/results/{DEFAULT_RESULT_IMAGE}',  # 始终使用默认图片
                'params': summary,
                'paramsObj': params
            })
    
    # 按日期降序排序
    params_files.sort(key=lambda x: x['date'], reverse=True)
    
    return jsonify({
        'success': True,
        'data': params_files
    })

if __name__ == '__main__':
    app.run(debug=True, host='0.0.0.0', port=5000) 